<?php

namespace App\Models;

use App\Models\AgentAccount;
use App\Models\AgentLoginLog;
use App\Models\AgentPrice;
use App\Models\AgentAccountDetail;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class Agent extends Model implements AuthenticatableContract
{
    use Authenticatable,HasPermissions, HasDateTimeFormatter,SoftDeletes;
    
    const DEFAULT_ID = 10;

    protected $fillable = ['username', 'password', 'name', 'avatar','last_ip','balance','withdraw',
        'parent_id',
        'from_code',
        'rake_back_rate',
        'withdraw_rate',
        'state',
        'wechat',
        'phone',
        'deduct',
        'deduct_counter'
    ];
    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        $connection = config('agent-admin.database.connection') ?: config('database.default');

        $this->setConnection($connection);

        $this->setTable(config('agent-admin.database.users_table'));

        parent::__construct($attributes);
    }
     /**
     * Get avatar attribute.
     *
     * @return mixed|string
     */
    public function getAvatar()
    {
        $avatar = $this->avatar;

        if ($avatar) {
            if (! URL::isValidUrl($avatar)) {
                $avatar = Storage::disk(config('agent-admin.upload.disk'))->url($avatar);
            }

            return $avatar;
        }

        return admin_asset(config('agent-admin.default_avatar') ?: 'https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1411764625,444874777&fm=26&gp=0.jpg');
    }

    /**
     * A user has and belongs to many roles.
     *
     * @return BelongsToMany
     */
    public function roles(): BelongsToMany
    {
        $pivotTable = config('agent-admin.database.role_users_table');

        $relatedModel = config('agent-admin.database.roles_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'agent_id', 'role_id')->withTimestamps();
    }

    protected static function booted()
    {
        static::created(function ($agent) {
            AgentAccount::Create([
                'agent_id'=>$agent->id,
                'balance'=>0,
                'profits'=>0,
                'withdrawed'=>0,
                'edit_code' => random(6)
            ]);
        });

        static::saved(function ($agent) {
            if(!boolval($agent->agentAccount)){
                AgentAccount::Create([
                    'agent_id'=>$agent->id,
                    'balance'=>0,
                    'profits'=>0,
                    'withdrawed'=>0,
                    'edit_code' => random(6)
                ]);
            }
            
        });

        static::deleted(function ($agent) {
            if(boolval($agent->agentAccount)){
                $agent->agentAccount->delete();
            }
            //删除代理登录记录
            AgentLoginLog::where('agent_id',$agent->id)->delete();
            //删除代理价格
            AgentPrice::where('agent_id',$agent->id)->delete();
            //删除相关打赏记录
            AgentAccountDetail::where('agent_id',$agent->id)->delete();
            
        });

    }

    /**
     * 判断是否允许查看菜单.
     *
     * @param array|Menu $menu
     *
     * @return bool
     */
    public function canSeeMenu($menu)
    {
        return true;
    }

    public function scopeEnable($query){
        return $query->where('state',1);
    }


    public function agentAccount(){
        return $this->hasOne(AgentAccount::class);
    }

    public function accountDetails(){
        return $this->hasMany(AgentAccountDetail::class);
    }
}
